package cn.itcast.oss.autoconfigure;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class OssTemplate {
    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    public String upload(String fileName, InputStream inputStream) {
        //创建客户端
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getKey(), ossProperties.getSecret());

        //设置文件最终的路径和名称
        String objectName = "images/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));

        //上传
        ossClient.putObject(ossProperties.getBucket(), objectName, inputStream);

        //关闭客户端
        ossClient.shutdown();

        return "https://" + ossProperties.getBucket() + "." + ossProperties.getEndpoint() + "/" + objectName;
    }
}
